<?php

namespace App\Common\Web;


use App\Common\Log;
use App\Common\Sys;
use App\Model\t_wx_reply;
use App\X\EHelper;
use XWX\Common\H;

class TempFile extends TempView
{
    public function __construct($file_name, $app_cookie)
    {
        $this->pub_file_name = $file_name;
        $this->pub_app_cookie = $app_cookie;
    }

    private $pub_file_name;
    private $pub_app_cookie;
    private $pub_TF;

    /**
     * @return CookieModel
     */
    public function funcAppCookie()
    {
        return $this->pub_app_cookie;
    }

    /**
     * 模板名称
     *
     * @return string
     */
    public function funcGetTF()
    {
        return $this->pub_TF;
    }

    /**
     * js类型
     *
     * @return bool
     */
    public function fileType()
    {
        $type = 'html';
        if (H::funcStrEndsWith($this->pub_file_name, '.js'))
        {
            $type = 'js';
        }
        else if (H::funcStrEndsWith($this->pub_file_name, '.css'))
        {
            $type = 'css';
        }


        return $type;
    }


    public function funcPageContentBefore()
    {
        $app_cookie = $this->funcAppCookie();

        $view_path = EHelper::funcGetConf('SYS.view');

        $this->pub_TF = $this->funcGetFile();


        $file_path_fix = "{$view_path}/{$app_cookie->getAppId()}/{$this->pub_TF}";
        $file_path = "{$file_path_fix}/{$this->pub_file_name}";

        //模板文件链接
        $this->pub_view_path = $file_path;
        Log::funcLog(__METHOD__, $file_path);


        //设置替换
        $replace_data = $this->funcGetReplaceData();
        $this->funcSetReplace($replace_data);
    }


    /**
     * 获取模板
     *
     * @return string
     */
    private function funcGetFile()
    {
        $app_cookie = $this->funcAppCookie();
        $wx_word = $app_cookie->funcGetWxWord();


        $entity_rapp = t_wx_reply::funcReplyApp($wx_word->app(), $wx_word->keyNum());

        $t = 't_001';//默认模板
        if (H::funcStrHasAnyText($entity_rapp->reply_app_file))
        {
            $t = $entity_rapp->reply_app_file;
        }

        return $t;
    }

    /**
     * 替换占位符
     */
    private function funcGetReplaceData()
    {
        $replace_data = [];


        //页面cookie
        $app_cookie = $this->funcAppCookie();
        foreach ($app_cookie->toArray() as $k => $v)
        {
            $key = str_replace('APP__', '', $k);
            $key = $this->funcReplaceBox($key);

            $replace_data[$key] = $v;
        }

        //静态资源域名
        $replace_data['{s_file_app}'] = Sys::funcStaticFileRoot() . "_app/{$app_cookie->getAppId()}/{$this->funcGetTF()}";


        return $replace_data;
    }


    private function funcReplaceBox($key)
    {
        return '{' . $key . '}';
    }
}